package com.atguigu.gulimail.product.exception;

import com.atguigu.common.exception.BizCodedEnum;
import com.atguigu.common.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理所有异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimail.product.controller")
//@ControllerAdvice(basePackages = "com.ayguigu.gulimail.product.controller")
public class GuliamilExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Response handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> map  = new HashMap<>();
        bindingResult.getFieldErrors().forEach((filerro)->{
            map.put(filerro.getField(),filerro.getDefaultMessage());
        });
        return  Response.error(BizCodedEnum.VAILD_EXCEPTION.getCode(),BizCodedEnum.VAILD_EXCEPTION.getMsg()).put("data",map);
    }

    //最大的异常处理类
    @ExceptionHandler(value = Exception.class)
    public Response handleException(Throwable throwable){


        log.error("出现错误",throwable);

        return Response.error(BizCodedEnum.UNKNOW_EXCEPTION.getCode(),BizCodedEnum.UNKNOW_EXCEPTION.getMsg());
    }

}
